<?php
if (!defined("_INDEX")) { header("Location: /"); die; }


/*
* -------------------------------------------------------
* User - class for working with Users
* -------------------------------------------------------
*/

class User {
	
	private $_userId = 0;
	private $_userLogin = "guest";
	private $_userSName = "";
	private $_userName = "гость";
	private $_userTName = "";
	private $_userType = 'guest';
	private $_db;
	
	function __construct (){
		global $db;
		$this->_db = $db;
		
		if (isset($_SESSION['userId']) && $_SESSION['userId'] != ''){
			$u = $this->_db->getRow("select `type`,`login`,`password` from `users` where `user_id` = '".$_SESSION['userId']."' limit 1");
			if (count($u) > 0)
				$this->login($u['login'],$u['password'],false,true);
		} elseif (isset($_COOKIE['_auhash'])) {
			$hash = $_COOKIE['_auhash'];
			$r_user = $this->_db->getRow("select * from `remember_users` where `hash` = '$hash' limit 1");
			if ($r_user){
				if ($r_user['before_time'] > time()){
					$u = $this->_db->getRow("select `type`,`login`,`password` from `users` where `user_id` = '".$r_user['user_id']."' limit 1");
					if (count($u) > 0)
						$this->login($u['login'],$u['password'],false,true);
				} else {
					setcookie("_auhash","",-1);
					$this->_db->sendQuery("delete from `remember_users` where `user_id` = '$r_user[user_id]' limit 1");
				}
			}
		}
	}
	
	public function login($login,$password,$remember=false,$without_pass=false){
		
		$l_user = $this->_db->getRow("select `user_id`,`salt`,`status` from `users` where `login` = '".$login."' limit 1");
		
		if ($l_user){
			
			// проверка на бан
			$banned = false;
			if ($l_user['status'] == "banned"){
				$ban_time = $this->_db->getCell("select `ban_time` from `ban_users` where `user_id` = '$l_user[user_id]' limit 1");
				if ($ban_time > time()){
					$banned = true;
				} else {
					$this->_db->sendQuery("update `users` set `status` = 'must_approve' where `user_id` = '$l_user[user_id]'");
					$this->_db->sendQuery("delete from `ban_users` where `user_id` = '$l_user[user_id]'");
				}
			}
		
			if (!$banned){
				
				// вход по логину
				if (!$without_pass)
					$pass = md5(md5($password).$l_user['salt']);
				else // вход по сессии
					$pass = $password;
				
				$auth = $this->_db->getRow("select * from `users` where `login` = '".$login."' and `password` = '".$pass."' limit 1");
				
				if ($auth) {
					
					session_register('userId');
					$_SESSION['userId'] = $auth["user_id"];
					$this->_userId = $auth["user_id"];
					$this->_userType = $auth["type"];
					$this->_userLogin = $auth["login"];
					$this->_userSName = $auth["sname"];
					$this->_userName = $auth["name"];
					$this->_userTName = $auth["tname"];
					
					// ставим куку
					if ($remember){
						$before = time() + 1209600;
						$hash = md5($auth["login"].$before);
						$user_agent = $_SERVER['HTTP_USER_AGENT'];
						setcookie("_auhash",$hash,$before,"/");
						// remember on 2 week
						$this->_db->sendQuery("insert into `remember_users` values (NULL,'$auth[user_id]','$hash','$before','$user_agent')");
					}
					
					// обновляем время
					$this->_db->sendQuery("update `users` set `last_time` = '".time()."', `last_ip` = '".$_SERVER['REMOTE_ADDR']."' where `user_id` = '".$auth["user_id"]."' limit 1");
					//удаляем неудачные авторизации
					$this->_db->sendQuery("delete from `auth` where `user_id` = '$auth[user_id]'");
					
					return $auth["user_id"];
				
				} else {
					
					// неудавшиеся авторизации
					$a_user = $this->_db->getRow("select `user_id`,`email` from `users` where `login` = '$login' limit 1");
					
					if ($auth = $this->_db->getRow("select `auth_id`,`count` from `auth` where `user_id` = '$a_user[user_id]' limit 1")){
						if ($auth['count'] >= 3){
							$this->_db->sendQuery("update `users` set `status` = 'banned' where `user_id` = '$a_user[user_id]' limit 1");
							$this->_db->sendQuery("insert into `ban_users` values(NULL,'$a_user[user_id]','".(time() + 86400)."')");
							$this->_db->sendQuery("delete from `auth` where `auth_id` = '$auth[auth_id]' limit 1");
						} else {
							$this->_db->sendQuery("update `auth` set `count` = `count` + 1 where `auth_id` = '$auth[auth_id]' limit 1");
						}
					} else {
						$this->_db->sendQuery("insert into `auth` values(NULL,'$a_user[user_id]','1')");
					}
					
					$this->logout();
				}
			} else {
				$this->logout();
			}
		} else {
			$this->logout();
		}
		
		return false;
	}
	
	public function logout(){
		setcookie("_auhash","",-1,"/");
		$user_id = isset($_SESSION['userId']) ? $_SESSION['userId'] : 0;
		$this->_db->sendQuery("delete from `remember_users` where `user_id` = '$user_id' limit 1");
		unset($_SESSION['userId']);
	}
	
	public function getUserId(){
		return $this->_userId;
	}
	
	public function getUserLogin(){
		return $this->_userLogin;
	}
	
	public function getFullName(){
		return $this->_userSName." ".$this->_userName." ".$this->_userTName;
	}
	
	public function getSName(){
		return $this->_userSName;
	}
	
	public function getName(){
		return $this->_userName;
	}
	
	public function getTName(){
		return $this->_userTName;
	}
	
	public function getUserType(){
		return $this->_userType;
	}
	
	public function isUser(){
		return ($this->_userId != 0);
	}
	
	public function isUsualUser(){
		return ($this->_userType == 'user');
	}
	
	public function isAdmin(){
		return ($this->_userType == 'administrator');
	}
	
	public function isCoordinator(){
		return ($this->_userType == 'coordinator1' || $this->_userType == 'coordinator2');
	}
	
	public function getCoordinatorType(){
		return ($this->_userType == 'coordinator1' ? 1 : ($this->_userType == 'coordinator2' ? 2 : 0));
	}
}



?>